﻿using Gadgeteer.Modules.GHIElectronics;
using Microsoft.SPOT;
using PJE.GlideEx;
using System;
using System.IO;

namespace SettingsTest
{
	public partial class Program
	{
		private const string FilePath = "Application.config";
		// This method is run when the mainboard is powered up or reset.   
		void ProgramStarted()
		{
			/*******************************************************************************************
			Modules added in the Program.gadgeteer designer view are used by typing 
			their name followed by a period, e.g.  button.  or  camera.
			
			Many modules generate useful events. Type +=<tab><tab> to add a handler to an event, e.g.:
				button.ButtonPressed +=<tab><tab>
			
			If you want to do something periodically, use a GT.Timer and handle its Tick event, e.g.:
				GT.Timer timer = new GT.Timer(1000); // every second (1000ms)
				timer.Tick +=<tab><tab>
				timer.Start();
			*******************************************************************************************/


			// Use Debug.Print to show messages in Visual Studio's "Output" window during debugging.
			Debug.Print("Program Started");

			sdCard0.SDCardMounted += sdCard_SDCardMounted;
		}

		void sdCard_SDCardMounted(SDCard sender, Gadgeteer.StorageDevice sdCard)
		{
			//Reads configuration file.
			using (Stream configStream = sdCard.OpenRead(FilePath))
			{
				//Loads settings.
				Settings.Load(configStream);
			}

			//Retrieves values.
			var points = (int)Settings.GetSetting("Points");

			if (points <= 0) return;

			var sx = (short[])Settings.GetSetting("Sx");
			var sy = (short[])Settings.GetSetting("Sy");
			var cx = (short[])Settings.GetSetting("Cx");
			var cy = (short[])Settings.GetSetting("Cy");

			Debug.Print("Settings Loaded");


			//Change values and save.
			Settings.SetSetting("Points", points);
			Settings.SetSetting("Sx", sx);
			Settings.SetSetting("Sy", sy);
			Settings.SetSetting("Cx", cx);
			Settings.SetSetting("Cy", cy);

			// Adds a value that contains the last save time.
			Settings.SetSetting("LastSaveTime", DateTime.Now);

			// Saves settings.
			using (Stream configStream = sdCard0.GetStorageDevice().OpenWrite(FilePath))
			{
				Settings.Save(configStream);
			}

			Debug.Print("Settings saved");

		}
	}
}
